<template>
  <div class="about">
    <div ref="list" class="scrollView" @scroll="onScroll">
      <!-- 虚拟列表 -->
      <div class="virtualScroller" :style="{ height: listHeight + 'px' }" />
      <div class="list" :style="{ transform: `translateY(${startOffset}px)` }">
        <div v-for="item in list" :key="item" class="item">
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [],
      listHeight: 0,
      itemSize: 50,
      containerHeight: 300,
      visibleCount: 6,
      data: [],
      startOffset: 0
    }
  },
  mounted() {
    const total = 100000
    const list = []
    for (let i = 0; i < total; i++) {
      list.push(i)
    }
    this.listHeight = list.length * this.itemSize
    this.data = list
    this.list = list.slice(0, 6)
  },
  methods: {
    onScroll() {
      // 当前滚动位置
      const scrollTop = this.$refs.list.scrollTop
      console.log(scrollTop, 'scrollTop---')
      // 列表开始索引
      const startIndex = Math.floor(scrollTop / this.itemSize)
      console.log('startIndex--', startIndex)
      // 列表结束索引
      const endIndex = Math.ceil((scrollTop + this.containerHeight) / this.itemSize)
      this.list = this.data.slice(startIndex, endIndex)
      // 列表移动距离
      this.startOffset = scrollTop - (scrollTop % this.itemSize)
      console.log(this.startOffset, 'this.startOffset---')
    }
  }
}
</script>
<style>
.scrollView {
  width: 200px;
  height: 300px;
  background-color: red;
  overflow-y: scroll;
  position: relative;
}
.item {
  height: 50px;
}
.list {
  position: absolute;
  top: 0;
  left: 0;
}
</style>
